import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useLayerStore } from './layer.js'

export const useHistoryStore = defineStore('history', () => {
  // 历史记录
  const history = ref([]) // 历史记录
  const currentIndex = ref(-1) // 当前历史记录索引
  const maxHistorySize = ref(100) // 最大历史记录数量
  const isRecording = ref(true) // 是否记录历史记录

  // 计算属性
  const canUndo = computed(() => currentIndex.value > 0) // 指针位置
  const canRedo = computed(() => currentIndex.value < history.value.length - 1) // 指针小于数组长度
  const historyCount = computed(() => history.value.length)
  const currentHistoryItem = computed(() => {
    if (currentIndex.value >= 0 && currentIndex.value < history.value.length) {
      return history.value[currentIndex.value]
    }
    return null
  })

  // Actions
  const addHistoryItem = (item) => {
    if (!isRecording.value) return

    // 移除当前位置之后的所有历史记录
    history.value = history.value.slice(0, currentIndex.value + 1)
    
    // 添加新的历史记录
    const historyItem = {
      id: generateId(),
      type: item.type,
      action: item.action,
      data: item.data,
      timestamp: Date.now(),
      description: item.description || generateDescription(item)
    }
    
    history.value.push(historyItem)
    currentIndex.value = history.value.length - 1
    
    // 限制历史记录数量
    if (history.value.length > maxHistorySize.value) {
      history.value.shift()
      currentIndex.value--
    }
  }

  // 批量操作：将一组操作作为一个历史节点写入
  const addBatchOperation = (operations, description = '') => {
    const item = {
      type: 'batch_operation',
      action: 'batch',
      data: { operations },
      description
    }
    addHistoryItem(item)
  }

  // 撤销
  const undo = () => {
    if (!canUndo.value) return
    
    const item = history.value[currentIndex.value]
    currentIndex.value--
    if (item) {
      applyHistoryItem(item, 'undo')
    }
  }

  // 重做
  const redo = () => {
    if (!canRedo.value) return
    currentIndex.value++
    const item = history.value[currentIndex.value]
    if (item) {
      applyHistoryItem(item, 'redo')
    }
  }

  // 跳转到指定历史记录
  const goToHistoryItem = (index) => {
    if (index < 0 || index >= history.value.length) return
    
    currentIndex.value = index
    const item = history.value[index]
    
    if (item) {
      applyHistoryItem(item, 'goto')
    }
  }

  const clearHistory = () => {
    history.value = []
    currentIndex.value = -1
  }

  const setRecording = (recording) => {
    isRecording.value = recording
  }

  const setMaxHistorySize = (size) => {
    maxHistorySize.value = size
    // 如果当前历史记录超过新的限制，移除多余的记录
    if (history.value.length > size) {
      const removeCount = history.value.length - size
      history.value = history.value.slice(removeCount)
      currentIndex.value = Math.max(0, currentIndex.value - removeCount)
    }
  }

  const getHistoryItems = (startIndex = 0, endIndex = -1) => {
    if (endIndex === -1) {
      endIndex = history.value.length
    }
    return history.value.slice(startIndex, endIndex)
  }

  const getHistoryItemById = (id) => {
    return history.value.find(item => item.id === id)
  }

  const removeHistoryItem = (id) => {
    const index = history.value.findIndex(item => item.id === id)
    if (index !== -1) {
      history.value.splice(index, 1)
      if (currentIndex.value >= index) {
        currentIndex.value--
      }
    }
  }

  const exportHistory = () => {
    return {
      history: history.value,
      currentIndex: currentIndex.value,
      maxHistorySize: maxHistorySize.value,
      exportTime: Date.now()
    }
  }

  const importHistory = (data) => {
    if (data.history && Array.isArray(data.history)) {
      history.value = data.history
      currentIndex.value = data.currentIndex || -1
      maxHistorySize.value = data.maxHistorySize || 50
    }
  }

  // 应用历史记录项
  const applyHistoryItem = (item, action) => {
    const layerStore = useLayerStore()
    switch (item.type) {
      case 'object_create':
        applyObjectCreate(item, action, layerStore)
        break
      case 'object_delete':
        applyObjectDelete(item, action, layerStore)
        break
      case 'object_modify':
        applyObjectModify(item, action, layerStore)
        break
      case 'object_move':
        applyObjectMove(item, action, layerStore)
        break
      case 'object_rotate':
        applyObjectRotate(item, action, layerStore)
        break
      case 'object_scale':
        applyObjectScale(item, action, layerStore)
        break
      case 'layer_visibility':
        applyLayerVisibility(item, action)
        break
      case 'canvas_settings':
        applyCanvasSettings(item, action)
        break
      case 'project_settings':
        applyProjectSettings(item, action)
        break
      case 'group_operation':
        applyGroupOperation(item, action)
        break
      case 'batch_operation':
        applyBatchOperation(item, action)
        break
      default:
        console.warn('未知的历史记录类型:', item.type)
    }
  }

  // 各种操作的应用函数

  /**
   * 应用对象创建历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectCreate = (item, action, layerStore) => {
    const object = item.data.object
    if (!object) return
    if (action === 'undo' || action === 'goto') {
      // 删除对象
      const layer = layerStore.findObjectLayer(object.id)
      if (layer) layerStore.removeObjectFromLayer(layer.id, object.id)
    } else if (action === 'redo') {
      // 重新创建对象
      layerStore.addObjectToLayer(object.layerId || 'furniture', { ...object })
    }
  }

  /**
   * 应用对象删除历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectDelete = (item, action, layerStore) => {
    const object = item.data.object
    const objectId = item.data.objectId || object?.id
    if (action === 'undo' || action === 'goto') {
      if (object) {
        layerStore.addObjectToLayer(object.layerId || 'furniture', { ...object })
      }
    } else if (action === 'redo') {
      if (objectId) {
        const layer = layerStore.findObjectLayer(objectId)
        if (layer) layerStore.removeObjectFromLayer(layer.id, objectId)
      }
    }
  }

  /**
   * 应用对象修改历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectModify = (item, action, layerStore) => {
    const { objectId, oldData, newData } = item.data
    const layer = layerStore.findObjectLayer(objectId)
    if (!layer) return
    const obj = layer.objects.find(o => o.id === objectId)
    if (!obj) return
    if (action === 'undo' || action === 'goto') {
      Object.assign(obj, oldData)
    } else if (action === 'redo') {
      Object.assign(obj, newData)
    }
  }

  /**
   * 应用对象移动历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectMove = (item, action, layerStore) => {
    const { objectId, oldPosition, newPosition } = item.data
    const layer = layerStore.findObjectLayer(objectId)
    if (!layer) return
    const obj = layer.objects.find(o => o.id === objectId)
    if (!obj) return
    const target = (action === 'undo' || action === 'goto') ? oldPosition : newPosition
    if (target) {
      obj.x = target.x
      obj.y = target.y
    }
  }

  /**
   * 应用对象旋转历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectRotate = (item, action, layerStore) => {
    const { objectId, oldRotation, newRotation } = item.data
    const layer = layerStore.findObjectLayer(objectId)
    if (!layer) return
    const obj = layer.objects.find(o => o.id === objectId)
    if (!obj) return
    obj.rotation = (action === 'undo' || action === 'goto') ? oldRotation : newRotation
  }

  /**
   * 应用对象缩放历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   * @param {Object} layerStore - 图层存储
   */
  const applyObjectScale = (item, action, layerStore) => {
    const { objectId, oldSize, oldPosition, newSize, newPosition } = item.data
    const layer = layerStore.findObjectLayer(objectId)
    if (!layer) return
    const obj = layer.objects.find(o => o.id === objectId)
    if (!obj) return
    const size = (action === 'undo' || action === 'goto') ? oldSize : newSize
    const pos = (action === 'undo' || action === 'goto') ? oldPosition : newPosition
    if (size) {
      obj.width = size.width
      obj.height = size.height
    }
    if (pos) {
      obj.x = pos.x
      obj.y = pos.y
    }
  }

  /**
   * 应用图层可见性历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   */
  const applyLayerVisibility = (item, action) => {
    if (action === 'undo') {
      // 撤销图层可见性变更
      // setLayerVisibility(item.data.layerId, item.data.oldVisible)
    } else if (action === 'redo') {
      // 重做图层可见性变更
      // setLayerVisibility(item.data.layerId, item.data.newVisible)
    }
  }

  /**
   * 应用画布设置历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   */
  const applyCanvasSettings = (item, action) => {
    if (action === 'undo') {
      // 撤销画布设置变更
      // updateCanvasSettings(item.data.oldSettings)
    } else if (action === 'redo') {
      // 重做画布设置变更
      // updateCanvasSettings(item.data.newSettings)
    }
  }

  /**
   * 应用项目设置历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   */
  const applyProjectSettings = (item, action) => {
    if (action === 'undo') {
      // 撤销项目设置变更
      // updateProjectSettings(item.data.oldSettings)
    } else if (action === 'redo') {
      // 重做项目设置变更
      // updateProjectSettings(item.data.newSettings)
    }
  }

  /**
   * 应用组操作历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   */
  const applyGroupOperation = (item, action) => {
    if (action === 'undo') {
      // 撤销组操作
      if (item.data.operation === 'group') {
        // ungroup(item.data.groupId)
      } else if (item.data.operation === 'ungroup') {
        // regroup(item.data.groupId, item.data.children)
      }
    } else if (action === 'redo') {
      // 重做组操作
      if (item.data.operation === 'group') {
        // group(item.data.children)
      } else if (item.data.operation === 'ungroup') {
        // ungroup(item.data.groupId)
      }
    }
  }

  /**
   * 应用批量操作历史记录
   * @param {Object} item - 历史记录项
   * @param {String} action - 操作类型：undo、redo、goto
   */
  const applyBatchOperation = (item, action) => {
    if (action === 'undo') {
      // 撤销批量操作
      item.data.operations.reverse().forEach(operation => {
        applyHistoryItem(operation, 'undo')
      })
    } else if (action === 'redo') {
      // 重做批量操作
      item.data.operations.forEach(operation => {
        applyHistoryItem(operation, 'redo')
      })
    }
  }

  // 生成历史记录描述
  const generateDescription = (item) => {
    const descriptions = {
      object_create: `创建${item.data.objectType || '对象'}`,
      object_delete: `删除${item.data.objectType || '对象'}`,
      object_modify: `修改${item.data.objectType || '对象'}`,
      object_move: `移动${item.data.objectType || '对象'}`,
      object_rotate: `旋转${item.data.objectType || '对象'}`,
      object_scale: `缩放${item.data.objectType || '对象'}`,
      layer_visibility: `切换图层可见性`,
      canvas_settings: `修改画布设置`,
      project_settings: `修改项目设置`,
      group_operation: item.data.operation === 'group' ? '组合对象' : '取消组合',
      batch_operation: `批量操作 (${item.data.operations && item.data.operations.length} 项)`
    }
    
    return descriptions[item.type] || '未知操作'
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  const reset = () => {
    history.value = []
    currentIndex.value = -1
    isRecording.value = true
  }

  return {
    // 状态
    history,
    currentIndex,
    maxHistorySize,
    isRecording,
    
    // 计算属性
    canUndo,
    canRedo,
    historyCount,
    currentHistoryItem,
    
    // Actions
    addBatchOperation,
    addHistoryItem,
    undo,
    redo,
    goToHistoryItem,
    clearHistory,
    setRecording,
    setMaxHistorySize,
    getHistoryItems,
    getHistoryItemById,
    removeHistoryItem,
    exportHistory,
    importHistory,
    reset
  }
})
